package com.lizemin.importcase.group;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @author lzm
 * @date 2025/10/30 18:56
 * @description 数据源分组，用来处理所有和数据库相关的配置类
 */
public class DataSourceGroup implements DeferredImportSelector.Group {

    private static final Logger log = LoggerFactory.getLogger(DataSourceGroup.class);

    private ArrayList<Entry> entries = new ArrayList<>();

    @Override
    public void process(AnnotationMetadata metadata, DeferredImportSelector selector) {
        String[] configClasses = selector.selectImports(metadata);
        for (String clazz : configClasses) {
            entries.add(new Entry(metadata, clazz));
        }
    }

    /**
     * 该方法会返回此分组下所有DeferredImportSelector最终要导入的配置类
     *
     * @return 该分组所有DeferredImportSelector最终要导入的配置类
     */
    @Override
    public Iterable<Entry> selectImports() {
        for (Entry entry : entries) {
            log.info("datasourceGroup中最终导入了配置类：{}", entry.getImportClassName());
        }
        // 这里还可以对entries进行排序，比如按照类名排序
        entries.sort(Comparator.comparing(Entry::getImportClassName));
        return entries;
    }

}
